package com.xxgc.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxgc.springboot.entity.News;
import com.xxgc.springboot.result.Result;
import com.xxgc.springboot.service.INewsService;
import com.xxgc.springboot.util.RedisClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 新闻 前端控制器
 * </p>
 *
 * @author Mr.Abel
 * @since 2022-10-19
 */
@RestController
@Api(tags = "新闻相关接口")
@RequestMapping("/news")
public class NewsController {

    @Resource
    private INewsService newsService;

    @Autowired
    private RedisClient rc;

    /**
     * 查询所有接口
     * @return
     */
    @ApiOperation(value = "新闻查询所有接口", notes = "查询所有接口")
    @GetMapping
    public Result<List<News>> findAll() {
        return Result.ok(newsService.list());
    }

    /**
     * 根据id查询数据接口
     * @param id
     * @return
     */
    @ApiOperation(value = "新闻查更具id查询", notes = "根据id查询数据接口")
    @GetMapping("/{id}")
        public Result<News> findOne(@PathVariable Integer id) {
        return Result.ok(newsService.getById(id));
    }

    /**
     * 分页查询接口
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "新闻分页查询接口", notes = "分页查询接口")
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        //判断reidis里面是否存在，如果存在就直接返回
        if(rc.exists("news:"+pageNum+":"+pageSize)){
            System.out.println("从缓存中读取");
            Page<News> page = (Page<News>) rc.get("news:" + pageNum + ":" + pageSize);
            return Result.ok(page);
        }

        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        Page<News> page = newsService.page(new Page<>(pageNum, pageSize), queryWrapper);

        //放入redis
        rc.set("news:"+pageNum+":"+pageSize,page);
        return Result.ok(page);
    }

    /**
     * 新增和更新接口
     * @param
     * @return
     */
    @ApiOperation(value = "新闻新增和更新接口", notes = "新增和更新接口")
    @PostMapping
    public Result save(@RequestBody News news) {
        newsService.saveOrUpdate(news);
        return Result.ok();
    }

    /**
     * 删除接口
     * @param id
     * @return
     */
    @ApiOperation(value = "新闻删除接口", notes = "删除接口")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        newsService.removeById(id);
        return Result.ok();
    }

    /**
     * 批量删除接口
     * @param ids
     * @return
     */
    @ApiOperation(value = "新闻批量删除接口", notes = "批量删除接口")
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        newsService.removeByIds(ids);
        return Result.ok();
    }
}